/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.muni.fi.pa165.bookingmanager.web;

import cz.muni.fi.pa165.bookingmanager.adapters.CustomerAdapter;
import cz.muni.fi.pa165.bookingmanager.adapters.HotelAdapter;
import cz.muni.fi.pa165.bookingmanager.adapters.ReservationAdapter;
import cz.muni.fi.pa165.bookingmanager.dto.CustomerDTO;
import cz.muni.fi.pa165.bookingmanager.dto.HotelDTO;
import cz.muni.fi.pa165.bookingmanager.dto.ReservationDTO;
import cz.muni.fi.pa165.bookingmanager.exceptions.IllegalOrphanException;
import cz.muni.fi.pa165.bookingmanager.exceptions.NonexistentEntityException;
import cz.muni.fi.pa165.bookingmanager.exceptions.PreexistingEntityException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.ejb.EJBAccessException;
import javax.ejb.EJBTransactionRolledbackException;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

import net.sourceforge.stripes.action.*;
import net.sourceforge.stripes.controller.LifecycleStage;
import net.sourceforge.stripes.validation.Validate;
import net.sourceforge.stripes.validation.ValidateNestedProperties;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.UnauthorizedException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author Radek Koubsky
 */
@UrlBinding("/admin/customer/{$event}")
public class CustomerActionBean extends MyActionBean {

    final static Logger log = LoggerFactory.getLogger(CustomerActionBean.class);
    private CustomerAdapter customerAdapter;
    private ReservationAdapter reservationAdapter;
    private HotelAdapter hotelAdapter;
    private List<CustomerDTO> list = new ArrayList<CustomerDTO>();
    @ValidateNestedProperties(value = {
        @Validate(on = {"add", "save"}, field = "firstName", required = true),
        @Validate(on = {"add", "save"}, field = "surName", required = true),
        @Validate(on = {"add", "save"}, field = "numberOfIdCard", required = true)
    })
    private CustomerDTO customer;    
    private String customerName;

    public CustomerActionBean() throws NamingException {
        Context ctx = new InitialContext();
        this.customerAdapter = (CustomerAdapter) ctx.lookup("java:global/cz.muni.fi.pa165.bookingmanager_booking_manager-web_war_1.0-SNAPSHOT/CustomerAdapterImpl!cz.muni.fi.pa165.bookingmanager.adapters.CustomerAdapter");
        this.reservationAdapter = (ReservationAdapter) ctx.lookup("java:global/cz.muni.fi.pa165.bookingmanager_booking_manager-web_war_1.0-SNAPSHOT/ReservationAdapterImpl!cz.muni.fi.pa165.bookingmanager.adapters.ReservationAdapter");
        hotelAdapter = (HotelAdapter) ctx.lookup("java:global/cz.muni.fi.pa165.bookingmanager_booking_manager-web_war_1.0-SNAPSHOT/HotelAdapterImpl!cz.muni.fi.pa165.bookingmanager.adapters.HotelAdapter");
        list = getCustomers();
    }

    @DefaultHandler
    public Resolution all() {
        log.debug("all()");
        return new ForwardResolution("/backend/customers/list.jsp");
    }    

    public Resolution add() throws IllegalOrphanException, PreexistingEntityException {
        log.debug("add() customer={}", customer);
        customerAdapter.createCustomer(customer);
        return new RedirectResolution(this.getClass(), "all");
    }

    public CustomerDTO getCustomer() {
        return customer;
    }

    public void setCustomer(CustomerDTO customer) {
        this.customer = customer;
    }

    @Before(stages = LifecycleStage.BindingAndValidation, on = {"edit", "save", "delete"})
    public void loadCustomerFromDatabase() {
        String ids = getContext().getRequest().getParameter("customer.id");
        if (ids == null) {
            return;
        }
        customer = customerAdapter.getCustomerById(Long.parseLong(ids));
    }

    public Resolution edit() {
        log.debug("edit() customer={}", customer);
        return new ForwardResolution("/backend/customers/edit.jsp");
    }

    public Resolution save() throws NonexistentEntityException, IllegalOrphanException, PreexistingEntityException, Exception {
        log.debug("save() customer={}", customer);
        customerAdapter.updateCustomer(customer);
        return new RedirectResolution(this.getClass(), "all");
    }

    public Resolution delete() throws NonexistentEntityException, IllegalOrphanException {
        log.debug("delete({})", customer.getId());
        
        
        customerAdapter.deleteCustomer(customer);
        return new RedirectResolution(this.getClass(), "all");
    }

    public String getCustomerName() {
        return customerName;
    }

    public void setCustomerName(String customerName) {
        this.customerName = customerName;
    }

    public List<CustomerDTO> getList() {
        if (this.list == null) {
            return null;
        }
        return Collections.unmodifiableList(list);
    }

    public void setList(List<CustomerDTO> list) {
        this.list = new ArrayList<CustomerDTO>();
        this.list.addAll(list);
    }

    public Resolution findCustomersByName() {
        if (customerName != null) {
            list = customerAdapter.findCustomersByName(customerName);
            return new ForwardResolution("/backend/customers/list.jsp");
        } else {
            return new RedirectResolution(this.getClass(), "all");
        }
    }

    public List<CustomerDTO> getCustomers() {
        return customerAdapter.findAllCustomers();
    }
}
